<?php

!defined('IN_APP') && exit('Access Denied');

class usermodel {

    var $db;
    var $base;

    function __construct(&$base) {
        $this->base = $base;
        $this->db = $base->db;
    }

    function get($uid) {
        $user = $this->db->fetch_first("SELECT * FROM " . DB_TABLEPRE . "user WHERE uid='$uid'");
        return $user;
    }

    function get_by_username($username) {
        $user = $this->db->fetch_first("SELECT * FROM " . DB_TABLEPRE . "user WHERE username='$username'");
        return $user;
    }

    function get_by_email($email) {
        $user = $this->db->fetch_first("SELECT * FROM " . DB_TABLEPRE . "user WHERE email='$email'");
        return $user;
    }

    function refresh($uid, $islogin=1) {
        @$sid = tcookie('sid');
        $this->base->user = $this->db->fetch_first("SELECT * FROM " . DB_TABLEPRE . "user WHERE uid='$uid'");
        $this->db->query("REPLACE INTO " . DB_TABLEPRE . "session (sid,uid,islogin,`time`) VALUES ('$sid',$uid,$islogin,{$this->base->time})");
        $password = $this->base->user['password'];
        $auth = strcode("$uid\t$password", AUTH_KEY, 'ENCODE');
        tcookie('auth', $auth, 2592000);
        tcookie('loginuser', '');
    }

    function logout() {
        $sid = $this->base->user['sid'];
        tcookie('sid', '', 0);
        tcookie('auth', '', 0);
        tcookie('loginuser', '', 0);
        if ($sid) {
            $this->db->query('DELETE FROM ' . DB_TABLEPRE . 'session WHERE sid=\'' . $sid . '\'');
        }
    }

    function save_code($code) {
        $uid = $this->base->user['uid'];
        $sid = $this->base->user['sid'];
        $islogin = $this->db->result_first("SELECT islogin FROM " . DB_TABLEPRE . "session WHERE sid='$sid'");
        $islogin = $islogin ? $islogin : 0;
        $this->db->query("REPLACE INTO " . DB_TABLEPRE . "session (sid,uid,code,islogin,`time`) VALUES ('$sid',$uid,'$code','$islogin',{$this->base->time})");
    }

    function get_code() {
        $sid = $this->base->user['sid'];
        return $this->db->result_first("SELECT code FROM " . DB_TABLEPRE . "session WHERE sid='$sid'");
    }

    function update($password, $avatar, $positionid, $areaid) {
        $this->db->query("UPDATE " . DB_TABLEPRE . "user SET password='$password',avatar='$avatar',positionid=$positionid,areaid=$areaid WHERE uid='{$this->base->user['uid']}'");
    }

    function update_avatar($avatar='') {
        $uid = $this->base->user['uid'];
        $this->db->query("UPDATE `" . DB_TABLEPRE . "user` SET `avatar`='$avatar' WHERE `uid`='$uid'");
    }

}

?>